package com.lsw.jgyf.components.okhttp;


import android.annotation.SuppressLint;

import com.lsw.jgyf.MyApplication;
import com.lsw.jgyf.components.exception.NoNetworkException;
import com.lsw.shareUser.ShareUserInfoUtil;
import com.lsw.util.LogUtils;
import com.lsw.util.NetworkUtil;
import com.lsw.util.StringUtil;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * author：lsw
 */
public class LoggingInterceptor implements Interceptor {
    @SuppressLint("LongLogTag")
    @Override
    public Response intercept(Chain chain) throws IOException {

        if (!NetworkUtil.isNetworkConnected(MyApplication.getMyApplication())) {
            throw new NoNetworkException("请开启网络连接！");
        } else if (!NetworkUtil.isMobileConnected(MyApplication.getMyApplication()) &&
                !NetworkUtil.isWifiConnected(MyApplication.getMyApplication())) {
            throw new NoNetworkException("当前网络不可用！");
        }
        Request request = chain.request();
        LogUtils.i("http--------", "request=" + request.toString());
        if (LogUtils.logdebug) {
            if (request.body() instanceof FormBody) {
                FormBody oldFormBody = (FormBody) request.body();
                for (int i = 0; i < oldFormBody.size(); i++) {
                    LogUtils.i("http--------", "body:" + oldFormBody.encodedName(i) + "=" + oldFormBody.encodedValue(i));
                }
            }
        }
        Response response = null;
        if (StringUtil.isNullOrEmpty(ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).getString(ShareUserInfoUtil.USER_TOKEN, ""))) {
            response = chain.proceed(request);
        } else {
            Request tokenRequest = request.newBuilder()
                    .addHeader("Authorization", ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).getString(ShareUserInfoUtil.USER_TOKEN, ""))
                    .build();
            LogUtils.i("http--------", "token=" + ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).getString(ShareUserInfoUtil.USER_TOKEN, ""));
            response = chain.proceed(tokenRequest);
        }
//        Response response = chain.proceed(request);

        ResponseBody responseBody = response.peekBody(1024 * 1024);
        String gson = responseBody.string();
        LogUtils.e("responseBody.string() = ", gson + ",head=" + response.headers().toString());
        String token = response.header("Authorization");
        if (!StringUtil.isNullOrEmpty(token)) {
            ShareUserInfoUtil.getInstance(MyApplication.getMyApplication()).setString(ShareUserInfoUtil.USER_TOKEN, token);
        }
        if (gson == null) {
            throw new NoNetworkException("后台数据异常！");
        }
        return response;
    }
}
